package swu.client;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import swu.filter.VeriFilter;
import swu.user.User;
import swu.user.UserRepo;
import swu.verification.VeriCodeServlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/clientLogin")
public class ClientLoginServlet extends HttpServlet
{

    UserRepo userRepo = new UserRepo();
    private Map<String, User> users = new HashMap<>();

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        List<User> userList = null;
        try
        {
            userList = this.userRepo.getAllUsers();
        } catch (SQLException e)
        {
            throw new RuntimeException(e);
        }

        for(User user:userList)
        {
            this.users.put(user.getName(),user);
        }

        String name = request.getParameter("user");
        String pass = request.getParameter("pass");
        String code = request.getParameter("code");

        HttpSession session = request.getSession(true);
        String authcode = (String) session.getAttribute(VeriCodeServlet.AUTH_CODE);
        if (authcode == null || !authcode.equalsIgnoreCase(code))
        {
            response.sendRedirect("./index.html");
            return;
        }

        User user = this.users.get(name);
        if (user != null)
        {
            if (user.getPassword().equals(pass))
            {
                response.addCookie(new Cookie("shoppingMall-user", name));
                session = request.getSession(true);
                session.setAttribute(VeriFilter.LOGIN_TAG, VeriFilter.LOGIN_SUCCESS);
                session.setAttribute("username",name);

                response.sendRedirect("./client/main.html");
                return;
            }
        }

        response.sendRedirect("./index.html");
    }
}
